package com.wholesale.utils;

import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Handler;

public class AsyncImageLoader {
	// 为了加快速度，在内存中开启缓存（主要应用于重复图片较多时，或者同一个图片要多次被访问，比如在ListView时来回滚动）
	private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
	private ExecutorService executorService = Executors.newFixedThreadPool(5); // 固定五个线程来执行任务
	private final Handler handler = new Handler();

	private static AsyncImageLoader instance ;
	
	public static AsyncImageLoader getInstance(){
		if(instance == null){
			instance = new AsyncImageLoader();
		}
		return instance ;
	}
	
	private AsyncImageLoader(){
		
	}
	
	public Drawable loadDrawable(final String imageUrl,
			final ImageCallback callback) {
		// 如果imageUrl在缓存中，从缓存中读取
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			Drawable drawable = softReference.get();
			// if (drawable != null) {
			return drawable;
			// }
		}
		// 如果缓存中没有，或者缓存取出来的是null，则从网络上取出数据，并将取出的数据缓存到内存中
		executorService.submit(new Runnable() {
			public void run() {
				final Drawable drawable = loadImageFromUrl(imageUrl);
				if(imageCache.size()>20){
					imageCache.clear();
				}
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				handler.post(new Runnable() {
					public void run() {
						if (drawable != null) {
							callback.imageLoaded(drawable, imageUrl);
						}
					}
				});
			}
		});
		return null;
	}

	public static Bitmap loadImageByUrl(String url) {
		System.gc();
		if (url == null || url.equals("")) {
			return null;
		} else if (!url.startsWith("http")) {
			url = Constants.IMAGE_URL + url;
		}
		Bitmap bitmap = null;
		InputStream is = null;
		try {
			URL m = new URL(url);
			URLConnection conn = m.openConnection();
			is = conn.getInputStream();
			byte[] imgData = readStream(is);
			bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
			// int length = (int) conn.getContentLength();
			// // ByteBuffer btyeBf = ByteBuffer.allocate(length);
			// if (length != -1) {
			// imgData = new byte[length];
			// byte[] temp=new byte[512];
			// int readLen=0;
			// int destPos=0;
			// while((readLen=is.read(temp))>0){
			// System.arraycopy(temp, 0, imgData, destPos, readLen);
			// destPos+=readLen;
			// }
			// bitmap=BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
			// }
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return bitmap;
	}

	/**
	 * 下载图片
	 * 
	 * @param url
	 * @return Drawable
	 */
	public static Drawable loadImageFromUrl(String url) {
		System.gc();
		if (url == null || url.equals("")) {
			return null;
		} else if (!url.startsWith("http")) {
			url = Constants.IMAGE_URL + url;
		}
		URL m;
		InputStream i = null;
		Drawable d = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
			if (i == null) {
				return null;
			}
			d = Drawable.createFromStream(i, "image.png");
		} catch (Exception e1) {
		
		}catch (OutOfMemoryError e) {
		     // 提示系统，进行内存回收
		     System.gc();
		}
		return d;
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {

		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
								: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		// canvas.setBitmap(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
				.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}

		@Override
		public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int b = read();
					if (b < 0) {
						break; // we reached EOF
					} else {
						bytesSkipped = 1; // we read one byte
					}
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}

	/**
	 * Get data from stream
	 * 
	 * @param inStream
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		outStream.close();
		inStream.close();
		return outStream.toByteArray();
	}

	/**
	 * 对外界开放的回调接口
	 * 
	 * @author hou jinghao
	 */
	public interface ImageCallback {
		// 注意 此方法是用来设置目标对象的图像资源
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}
}
